package com.aldobucchi.x.flash.events
{
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IEventDispatcher;




/**
 * Dispatched when the intercepted event is fired.
 * You can call preventDefault() to intercept the event and 
 * keep it from getting to the original listener
 * 
 *  @eventType com.aldobucchi.x.flash.events.EventHookEvent
 */
[Event(name="fire", type="com.aldobucchi.x.flash.events.EventHookEvent")]






	public class EventListenerProxy extends EventDispatcher
	{
		
		
		
		private var spec:EventListenerSpec;
		
		private var modifiedSpec:EventListenerSpec;
		
		private var dispatcher:IEventDispatcher;



		public function EventListenerProxy( spec:EventListenerSpec, dispatcher:IEventDispatcher )
		{
		
			this.spec 			= spec;
			this.dispatcher 	= dispatcher;			

			modifiedSpec = new EventListenerSpec( 
							spec.type, 
							handleEvent, 
							spec.useCapture, 
							spec.priority, 
							spec.useWeakReference 
							);
			
			modifiedSpec.addToDispatcher( dispatcher );
			
		}
		
		
		
		
		
		private function handleEvent( event:Event ):void
		{
			
			var e:EventHookEvent = new EventHookEvent( EventHookEvent.FIRE, false, true, event );
			
			dispatchEvent( e );
			
			if ( e.isDefaultPrevented( ) )
				return;
							
			spec.listener.apply( null, [ event ] );
			
		}
		
		
		
		public function continueOriginalEventFlow( detainedOriginalEvent:Event ):void
		{
			spec.listener.apply( null, [ detainedOriginalEvent ] );
		}
		
		
		
		
		public function remove( ):void
		{
			modifiedSpec.removeFromDispatcher( dispatcher );
		}
		
		
	}
	
}

